package com.qywx.utils;

import com.qywx.entity.DepartmentEntity;
import lombok.experimental.UtilityClass;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName TreeUtil
 * @Description: TODO
 * @Author wmj
 * @Date 2020/3/13
 * @Version V1.0
 **/
@UtilityClass
public class TreeUtil {
    /**
     * 4      * 两层循环实现建树
     * 5      *
     * 6      * @param treeNodes 传入的树节点列表
     * 7      * @return
     * 8
     */
    public <T extends DepartmentEntity> List<T> bulid(List<T> treeNodes, Long root) {
        List<T> trees = new ArrayList<>();
        for (T treeNode : treeNodes) {
            if (root == treeNode.getParentid()) {
                trees.add(treeNode);
            }
            //获取二级目录
            for (T it : treeNodes) {
                Long parentid = it.getParentid();
                Long id = treeNode.getId();
                if (it.getParentid() == treeNode.getId()) {
                    if (treeNode.getChildren() == null) {
                        treeNode.setChildren(new ArrayList<>());
                    }
                   // treeNode.add(it);
                }
            }
        }
        return trees;
    }

    /**
     * 32      * 使用递归方法建树
     * 33      *
     * 34      * @param treeNodes
     * 35      * @return
     * 36
     */
    public <T extends DepartmentEntity> List<T> buildByRecursive(List<T> treeNodes, Long root) {
        List<T> trees = new ArrayList<T>();
        for (T treeNode : treeNodes) {
            if (root == treeNode.getParentid()) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        for (T treeNode : trees) {
            if(treeNode.getChildren() !=null){
                List<DepartmentEntity> children = treeNode.getChildren();
            }
        }

        return trees;
    }

    /**
     * 48      * 递归查找子节点
     * 49      *
     * 50      * @param treeNodes
     * 51      * @return
     * 52
     */
    public <T extends DepartmentEntity> T findChildren(T treeNode, List<T> treeNodes) {
        for (T it : treeNodes) {
            if (treeNode.getId() == it.getParentid()) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
               // treeNode.add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }
}
